import cv2
import time


def video_monitor():
    # 打开默认摄像头（0表示默认摄像头，多个摄像头可尝试1,2等）
    cap = cv2.VideoCapture(0)

    # 检查摄像头是否成功打开
    if not cap.isOpened():
        print("无法打开摄像头")
        return

    # 设置窗口名称
    window_name = "实时视频监控"
    cv2.namedWindow(window_name, cv2.WINDOW_NORMAL)

    # 可选：设置视频分辨率
    cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)

    print("开始实时监控...")
    print("操作说明:")
    print("  - 按 's' 键保存当前帧")
    print("  - 按 'q' 键退出监控")

    frame_count = 0
    start_time = time.time()

    while True:
        # 读取一帧视频
        ret, frame = cap.read()

        # 如果读取失败，退出循环
        if not ret:
            print("无法接收帧 (可能已到达流的末尾)。退出...")
            break

        # 计算并显示帧率
        frame_count += 1
        elapsed_time = time.time() - start_time
        fps = frame_count / elapsed_time if elapsed_time > 0 else 0
        cv2.putText(frame, f"FPS: {fps:.1f}", (10, 30),
                    cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)

        # 显示日期时间
        current_time = time.strftime("%Y-%m-%d %H:%M:%S")
        cv2.putText(frame, current_time, (10, frame.shape[0] - 10),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2)

        # 显示帧
        cv2.imshow(window_name, frame)

        # 等待按键输入
        key = cv2.waitKey(1) & 0xFF

        # 按 's' 键保存当前帧
        if key == ord('s'):
            filename = f"capture_{time.strftime('%Y%m%d_%H%M%S')}.jpg"
            cv2.imwrite(filename, frame)
            print(f"已保存帧到 {filename}")

        # 按 'q' 键退出
        elif key == ord('q'):
            print("退出监控...")
            break

    # 释放资源
    cap.release()
    cv2.destroyAllWindows()


if __name__ == "__main__":
    video_monitor()
